#include"snakeLinux.h"

// 游戏初始化
void initGame() {
    game.currentDir = DIR_RIGHT;
    game.lastDir = DIR_RIGHT;
    game.gameOver = false;
    game.score = 0;
    game.speed = 200000;  // 单位：微秒
    game.level = 1;
    obstacleCount = 0;
    isPaused = false;
}

// 暂停界面
void showPauseScreen() {
    clearScreen();
    initWall();
    
    setCursorPosition(WIDE/2 - 5, HIGH/2);
    printf("Game is Paused");
    
    setCursorPosition(WIDE/2 - 10, HIGH/2 + 1);
    printf("Press Space to Continue");

    setCursorPosition(WIDE/2 - 5, HIGH/2 + 2);
    printf("Press Q to Quit");

    showLevelInfo();
}

// 恢复游戏界面
void resumeGameScreen() {
    clearScreen();
    initWall();
    initUI();
}

// 初始化蛇
void initSnake() {
    snake.size = 3;
    for(size_t i = 0; i < snake.size; i++) {
        snake.body[i].X = WIDE/2 - i;
        snake.body[i].Y = HIGH/2;
    }
}

// 初始化食物
void initFood() {
    bool isOnSnake;
    do {
        isOnSnake = false;
        food.X = rand() % (WIDE - 2) + 1;
        food.Y = rand() % (HIGH - 2) + 1;

        // 检查是否与蛇身重叠
        for(size_t i = 0; i < snake.size; i++) {
            if(food.X == snake.body[i].X && food.Y == snake.body[i].Y) {
                isOnSnake = true;
                break;
            }
        }
        
        // 检查是否与障碍物重叠
        for(int i = 0; i < obstacleCount; i++) {
            if(food.X == obstacles[i].X && food.Y == obstacles[i].Y) {
                isOnSnake = true;
                break;
            }
        }
    } while(isOnSnake);
}

int min(int num1,int num2){
    if(num1>=num2){
        return num2;
    }
    else{
        return num1;
    }
}

// 初始化障碍物
void initObstacle() {
    obstacleCount = 0;
    int count = game.level * 6;
    if(count > MAX_OBSTACLES) count = MAX_OBSTACLES;
    
    for(int i = 0; i < count; ) {
        bool validPosition;
        do {
            validPosition = true;
            obstacles[i].X = rand() % (WIDE - 2) + 1;
            obstacles[i].Y = rand() % (HIGH - 2) + 1;
            
            // 检查是否与蛇身重叠
            for(size_t j = 0; j < snake.size; j++) {
                if(obstacles[i].X == snake.body[j].X && obstacles[i].Y == snake.body[j].Y) {
                    validPosition = false;
                    break;
                }
            }
            
            // 检查是否与食物重叠
            if(obstacles[i].X == food.X && obstacles[i].Y == food.Y) {
                validPosition = false;
            }
            
            // 检查是否与其他障碍物重叠
            for(int j = 0; j < i; j++) {
                if(obstacles[i].X == obstacles[j].X && obstacles[i].Y == obstacles[j].Y) {
                    validPosition = false;
                    break;
                }
            }
        } while(!validPosition);
        
        obstacleCount++;
        i++;
        
        // 随机决定是否生成连续障碍物
        if(i < count && rand() % 2 == 0) {
            int maxChain = min(5, count - i); 
            int chainLength = rand() % maxChain + 1; 
            
            int direction = rand() % 4; 
            int dx = 0, dy = 0;
            
            switch(direction) {
                case 0: dy = -1; break;
                case 1: dx = 1; break;
                case 2: dy = 1; break;
                case 3: dx = -1; break;
            }
            
            for(int j = 0; j < chainLength && i < count; j++) {
                validPosition = false;
                int tryCount = 0;
                
                while(!validPosition && tryCount < 10) {
                    tryCount++;
                    obstacles[i].X = obstacles[i-1].X + dx;
                    obstacles[i].Y = obstacles[i-1].Y + dy;
                    
                    if(obstacles[i].X < 1 || obstacles[i].X >= WIDE - 1 || 
                       obstacles[i].Y < 1 || obstacles[i].Y >= HIGH - 1) {
                        validPosition = false;
                        //换个方向
                        direction = (direction + 1) % 4;
                        switch(direction) {
                            case 0: dx = 0; dy = -1; break;
                            case 1: dx = 1; dy = 0; break;
                            case 2: dx = 0; dy = 1; break;
                            case 3: dx = -1; dy = 0; break;
                        }
                        continue;
                    }
                    
                    validPosition = true;
                    
                    // 检查是否与蛇身重叠
                    for(size_t j = 0; j < snake.size; j++) {
                        if(obstacles[i].X == snake.body[j].X && obstacles[i].Y == snake.body[j].Y) {
                            validPosition = false;
                            break;
                        }
                    }
                    
                    // 检查是否与食物重叠
                    if(obstacles[i].X == food.X && obstacles[i].Y == food.Y) {
                        validPosition = false;
                    }
                    
                    // 检查是否与其他障碍物重叠
                    for(int k = 0; k < i; k++) {
                        if(obstacles[i].X == obstacles[k].X && obstacles[i].Y == obstacles[k].Y) {
                            validPosition = false;
                            break;
                        }
                    }
                }
                
                if(validPosition) {
                    obstacleCount++;
                    i++;
                } else {
                    break; 
                }
            }
        }
    }
}

// 更新关卡
void updateLevel() {
    int newLevel = game.score / 30 + 1;
    if(newLevel > game.level) {
        game.level = newLevel;
        if(game.speed > 50000) {
            game.speed -= 10000;  // 加快速度
        }
        
        setCursorPosition(WIDE/2 - 5, HIGH/2);
        printf("LEVEL UP! %d", game.level);
        fflush(stdout);
        usleep(1000000);  // 暂停1秒
        initObstacle();
    }
}

// 处理输入
void handleInput() {
    if(kbhit()) {
        char key = getch();
        switch(key) {
            case 'W':
            case 'w':
                if(game.lastDir != DIR_DOWN) game.currentDir = DIR_UP;
                break;
            case 'S':
            case 's':
                if(game.lastDir != DIR_UP) game.currentDir = DIR_DOWN;
                break;
            case 'A':
            case 'a':
                if(game.lastDir != DIR_RIGHT) game.currentDir = DIR_LEFT;
                break;
            case 'D':
            case 'd':
                if(game.lastDir != DIR_LEFT) game.currentDir = DIR_RIGHT;
                break;
            case 'Q':
            case 'q':
                game.gameOver = true;
                break;
            case ' ':
                isPaused = !isPaused;
                if(isPaused) {
                    showPauseScreen();
                } else {
                    resumeGameScreen();
                }
                break;
        }
    }
}

// 移动蛇
void moveSnake() {
    lastX = snake.body[snake.size - 1].X;
    lastY = snake.body[snake.size - 1].Y;
    game.lastDir = game.currentDir;

    // 移动身体
    for(size_t i = snake.size - 1; i > 0; i--) {
        snake.body[i].X = snake.body[i - 1].X;
        snake.body[i].Y = snake.body[i - 1].Y;
    }

    // 移动头部
    switch(game.currentDir) {
        case DIR_UP: snake.body[0].Y--; break;
        case DIR_DOWN: snake.body[0].Y++; break;
        case DIR_LEFT: snake.body[0].X--; break;
        case DIR_RIGHT: snake.body[0].X++; break;
    }
}

// 检查碰撞
void checkCrush() {
    if(isPaused) return;

    // 撞墙
    if(snake.body[0].X <= 0 || snake.body[0].X >= WIDE - 1 ||
       snake.body[0].Y <= 0 || snake.body[0].Y >= HIGH - 1) {
        game.gameOver = true;
    }

    // 撞自己
    for(size_t i = 1; i < snake.size; i++) {
        if(snake.body[0].X == snake.body[i].X && snake.body[0].Y == snake.body[i].Y) {
            game.gameOver = true;
        }
    }

    // 撞障碍物
    for(int i = 0; i < obstacleCount; i++) {
        if(snake.body[0].X == obstacles[i].X && snake.body[0].Y == obstacles[i].Y) {
            game.gameOver = true;
        }
    }

    // 吃食物
    if(snake.body[0].X == food.X && snake.body[0].Y == food.Y) {
        snake.size++;
        game.score += 10;
        updateLevel();
        initFood();
        if(game.score % (50 * game.level) == 0) {
            initObstacle();
        }
    }
}

// 初始化墙壁
void initWall() {
    for(int i = 0; i < WIDE; i++) {
        setCursorPosition(i, 0);
        putchar('#');
        setCursorPosition(i, HIGH - 1);
        putchar('#');
    }
    for(int i = 1; i < HIGH - 1; i++) {
        setCursorPosition(0, i);
        putchar('#');
        setCursorPosition(WIDE - 1, i);
        putchar('#');
    }
}

// 初始化UI
void initUI() {
    char screenBuffer[HIGH][WIDE];
    memset(screenBuffer, ' ', sizeof(screenBuffer));

    // 绘制蛇
    for(size_t i = 0; i < snake.size; i++) {
        screenBuffer[snake.body[i].Y][snake.body[i].X] = (i == 0) ? '@' : '*';
    }

    // 绘制食物
    screenBuffer[food.Y][food.X] = '$';

    // 绘制障碍物
    for(int i = 0; i < obstacleCount; i++) {
        screenBuffer[obstacles[i].Y][obstacles[i].X] = '#';
    }

    // 刷新屏幕
    for(int y = 1; y < HIGH - 1; y++) {
        setCursorPosition(1, y);
        for(int x = 1; x < WIDE - 1; x++) {
            putchar(screenBuffer[y][x]);
        }
    }
    showLevelInfo();
}

// 显示等级信息
void showLevelInfo() {
    setCursorPosition(2, HIGH);
    printf("SCORE: %d", game.score);
    
    setCursorPosition(2, HIGH + 1);
    printf("LEVEL: %d", game.level);
    
    setCursorPosition(2, HIGH + 2);
    printf("OBSTACLES: %d", obstacleCount);

    setCursorPosition(2, HIGH + 3);
    printf("Controls: W/S/A/D to move, Space to pause, Q to quit");
    fflush(stdout);
}

// 游戏主循环
void playGame() {
    initGame();
    initSnake();
    initFood();
    clearScreen();
    initWall();
    initObstacle();
    initUI();

    while(!game.gameOver) {
        handleInput();
        if(isPaused) {
            usleep(300000);
            continue;
        }
        moveSnake();
        checkCrush();
        if(!game.gameOver) {
            initUI();
        }
        usleep(game.speed);  // 控制游戏速度
    }
}